package com.driving.code.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.driving.code.entity.*;
import com.driving.code.service.GradeService;
import com.driving.code.service.TUserService;
import com.driving.code.service.UserRoleService;
import com.driving.code.utils.EmailCodeUtil;
import com.driving.code.utils.MyUsernamePasswordToken;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.crypto.hash.Md5Hash;

import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("user")
public class TUserController {
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Resource
    private TUserService tUserService;
    @Resource
    private GradeService gradeService;

    @Resource
    private UserRoleService userRoleService;

    /**
     * 注册方法
     *
     * @param tUser
     * @return
     */
    @RequestMapping("register")
    public String register(TUser tUser, String code) {
        String judge = judge(tUser, code);
        if (!judge.equals("没错")) {
            return judge;
        }
        boolean save = saveUser(tUser);
        if (save) {
            return "1";
        }
        return "0";
    }

    @RequestMapping("adminRegister")
    public String adminRegister(TUser tUser, String code) {
        String judge = judge(tUser, code);
        if (!judge.equals("没错")) {
            return judge;
        }
        tUser.setApprove(1);//approve 1 代表发出申请
        boolean save = saveUser(tUser);
        if (save) {
            return "1";
        }
        return "0";
    }

    public String judge(TUser tUser, String code) {
        TUser one = tUserService.getOne(new QueryWrapper<TUser>().lambda().eq(TUser::getUserAccount, tUser.getUserAccount()));
        if (one != null) {
            return "2";
        }
        if (code == null || "".equals(code)) {
            return "3";
        }
        boolean b;
        try {
            b = EmailCodeUtil.checkCode(tUser.getUserEmail(), code);
        }
        catch (NullPointerException e) {
            return "5";
        }

        if (!b) {
            return "4";
        }
        return "没错";
    }

    private boolean saveUser(TUser tUser) {
        tUser.setUserImage("http://localhost:8080/image/front/face_nomal.png");
        String code = EmailCodeUtil.getCode();//生成5位数的随机盐，用于密码加密
        tUser.setUserSalt(code);
        Md5Hash md5Hash = new Md5Hash(tUser.getUserPassword(), code, 1024); //对密码进行加密处理
        String password = md5Hash.toHex();
        tUser.setUserPassword(password);
        return tUserService.save(tUser);
    }

    @RequestMapping("updatePassWord")
    public String updatePassWord(HttpSession session, TUser tUser, String password) {
        TUser user = (TUser) session.getAttribute("user");
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(user.getUserAccount(), tUser.getUserPassword(), "UserRealm");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        user.setUserPassword(password);
        String code = EmailCodeUtil.getCode();//生成5位数的随机盐，用于密码加密
        user.setUserSalt(code);
        Md5Hash md5Hash = new Md5Hash(user.getUserPassword(), code, 1024); //对密码进行加密处理
        String password1 = md5Hash.toHex();
        user.setUserPassword(password1);
        boolean b = tUserService.updateById(user);
        if (b) {
            subject.logout();
            return "4";
        }
        return "0";
    }

    @RequestMapping("login")
    public String login(String userAccount, String password) {
        TUser user = tUserService.getOne(new QueryWrapper<TUser>().lambda().eq(TUser::getUserAccount, userAccount).ne(TUser::getApprove, 0));
        if (user != null) {
            return "4";
        }
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(userAccount, password, "UserRealm");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return "0";
    }

    /**
     * 退出方法
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "1";
    }

    /**
     * 修改照片
     *
     * @return
     */
    @RequestMapping("updateImage")
    public void updateImage(@RequestBody TUser user_post, HttpSession session) {
        TUser user = (TUser) session.getAttribute("user");
        user.setUserImage(user_post.getUserImage());
        tUserService.updateById(user);
        session.setAttribute("user", user);
    }

    /**
     * 获取我的个人信息
     *
     * @return
     */
    @RequestMapping("getMyInformation")
    @ResponseBody
    public TUser getMyInformation(HttpSession session) {
        TUser user = (TUser) session.getAttribute("user");
        TUser tUser = tUserService.getById(user.getUserId());
        return tUser;
    }

    @RequestMapping("searchScore")
    @ResponseBody
    public Grade searchScore(HttpSession session) {
        TUser user = (TUser) session.getAttribute("user");
        List<Grade> list = gradeService.list(new QueryWrapper<Grade>().lambda().eq(Grade::getGradeLearner, user.getUserId()));
        Grade grade = null;
        if (list.size() == 0) {
            grade = new Grade();
            grade.setGradeScore(0);
            grade.setGradeExamTime(0);
            grade.setGradeSubject("未参加考试");
            list.add(grade);
        } else {
            grade = list.get(list.size() - 1);
            if ("1".equals(grade.getGradeSubject())){
                grade.setGradeSubject("科目一");
            }else
            grade.setGradeSubject("科目四");
        }
        session.setAttribute("grade", grade);
        return grade;
    }


    @RequestMapping("getApproveUser")
    public ParseData getApproveUser(@RequestParam(value = "page", required = false, defaultValue = "1") Integer current,
                                    @RequestParam(value = "limit", required = false, defaultValue = "12") Integer size,
                                    @RequestParam(value = "search", required = false) String search) {
        IPage<TUser> page = new Page(current, size);
        LambdaQueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>().lambda();
        if (search != null && !search.equals("")) {
            queryWrapper.like(TUser::getUserName, search);
        }
        queryWrapper.ne(TUser::getApprove, 0);
        return getParseData(page, queryWrapper);
    }

    @RequestMapping("getCancelApprove")
    public ParseData getCancelApprove(@RequestParam(value = "page", required = false, defaultValue = "1") Integer current,
                                      @RequestParam(value = "limit", required = false, defaultValue = "12") Integer size,
                                      @RequestParam(value = "search", required = false) String search,
                                      HttpSession session) {
        IPage<TUser> page = new Page(current, size);
        boolean flag=false;
        LambdaQueryWrapper<TUser> queryWrapper = new QueryWrapper<TUser>().lambda();
        TUser sessionUser = (TUser) session.getAttribute("user");
        LambdaQueryWrapper<TUser> eq = new QueryWrapper<TUser>().lambda().eq(TUser::getApprove, 0);
        List<TUser> list = tUserService.list(eq);
        if (search != null && !search.equals("")) {
            list = tUserService.list(eq.like(TUser::getUserName, search));
        }
        for (TUser user : list) {
            UserRole userRole = userRoleService.getOne(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getUserId()));
            if (userRole != null && !sessionUser.getUserId().equals(user.getUserId())) {
                queryWrapper.or().eq(TUser::getUserId, user.getUserId());
                flag=true;
            }
        }
            if (!flag){
            queryWrapper.eq(TUser::getUserId,0);//如果没有查找到数据，就让查询封装对象查询userid=0的数据。
            }

        return getParseData(page, queryWrapper);
    }

    private ParseData getParseData(IPage<TUser> page, LambdaQueryWrapper<TUser> queryWrapper) {
        IPage<TUser> userIPage = tUserService.page(page, queryWrapper);
        ParseData<TUser> parseData = new ParseData<>();
        parseData.setData(userIPage.getRecords());
        parseData.setCode(0);
        parseData.setCount(userIPage.getTotal());
        parseData.setMsg("请求成功");
        return parseData;
    }

    @RequestMapping("setApproveUser")
    public String setApproveUser(Integer userId) {
        TUser user = tUserService.getById(userId);
        user.setApprove(0);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(1);
        boolean save = userRoleService.save(userRole);
        boolean b = tUserService.updateById(user);
        if (b && save) {
            return "1";
        }
        return "0";
    }

    @RequestMapping("setCancelUser")
    public String setCancelUser(Integer userId) {
        if (userId.equals(1)) {
            return "2";
        }

        boolean removeRU = userRoleService.remove(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userId));
        if (removeRU) {
            return "1";
        }
        return "0";
    }

    /**
     * @param subject            主题
     * @param text               内容
     * @param setFrom            发送人的邮箱
     * @param setTo              接受人的邮箱
     * @throws MessagingException
     */

    public void sendMail(String subject, String text,  String setFrom, String setTo) throws javax.mail.MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject(subject);
        helper.setText(text, true);
        helper.setFrom(setFrom);
        helper.setTo(setTo);
        javaMailSender.send(mimeMessage);
    }

    @RequestMapping("sendCode")
    public String sendCode(TUser tUser) throws javax.mail.MessagingException {
        String code1 = EmailCodeUtil.getCode();
        try {
             EmailCodeUtil.setVeriCode(tUser.getUserEmail(), code1);
        } catch (JedisConnectionException e) {
            return "2";
        }
        sendMail("验证码", code1+"  验证码三分钟有效，请勿转告他人",  "1830626823@qq.com", tUser.getUserEmail());
        return "1";


    }
}

